import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { SheetData, Cell } from '../types/sheet';

export const useSheetStore = defineStore('sheet', () => {
  const currentSheet = ref<SheetData>({
    id: '',
    name: '',
    cells: {},
    collaborators: []
  });

  const socket = ref<WebSocket | null>(null);

  const initializeWebSocket = () => {
    socket.value = new WebSocket('ws://localhost:3000');
    
    socket.value.onmessage = (event) => {
      const data = JSON.parse(event.data);
      handleWebSocketMessage(data);
    };
  };

  const handleWebSocketMessage = (data: any) => {
    switch (data.type) {
      case 'SHEET_DATA':
        currentSheet.value = data.sheet;
        break;
      case 'CELL_UPDATE':
        updateCell(data.cellId, data.cell);
        break;
      case 'USER_JOINED':
        currentSheet.value.collaborators.push(data.userId);
        break;
      case 'USER_LEFT':
        const index = currentSheet.value.collaborators.indexOf(data.userId);
        if (index > -1) {
          currentSheet.value.collaborators.splice(index, 1);
        }
        break;
    }
  };

  const updateCell = (cellId: string, cell: Cell) => {
    currentSheet.value.cells[cellId] = cell;
  };

  const sendCellUpdate = (cellId: string, cell: Cell) => {
    if (socket.value?.readyState === WebSocket.OPEN) {
      socket.value.send(JSON.stringify({
        type: 'CELL_UPDATE',
        sheetId: currentSheet.value.id,
        cellId,
        cell
      }));
    }
  };

  return {
    currentSheet,
    initializeWebSocket,
    updateCell,
    sendCellUpdate
  };
}); 